package com.hxqc.basic.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;

import com.hxqc.basic.common.Constants;
import com.hxqc.basic.common.MD5;
import com.hxqc.basic.serivce.SysUserService;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/sys")
public class SysUserController {

	private static Logger logger = LoggerFactory.getLogger(SysUserController.class);
	@Autowired
	private ServletContext servletContext;
	@Resource
	private SysUserService sysUserService;
	
	/**
	 * 用户登录
	 * @param user_id
	 * @param password
	 * @param session
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/login")
	public Map<String, Object> login(String user_id, String password, HttpSession session,HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> user = sysUserService.selectSysUserById(user_id);
		if (user != null) {
			if(user.get("user_status").equals("1")){
				result.put("optFlag", "N");
				result.put("optDesc", "用户已被禁用!");
				return result;
			}
			// 判断密码
			String user_pwd = String.valueOf(user.get("password"));
			password = new MD5().getMD5ofStr(password.trim());
			if (user_pwd.equals(password)) {
				// 登录成功。
				initUserRight(user_id, session);
				user.remove("password");
				user.put("login_ip", request.getRemoteAddr());
				session.setAttribute(Constants.USER_SESSION_KEY, user);
			} else {
				result.put("optFlag", "N");
				result.put("optDesc", "密码输入不正确!");
				return result;
			}
			result.put("optFlag", "Y");
		} else {
			result.put("optFlag", "N");
			result.put("optDesc", "用户名或密码错误!");
		}
		logger.info(result.toString());
		return result;
	}
	
	/**
	 * 退出
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/logout")
	public RedirectView logout(HttpSession session) {
		session.removeAttribute(Constants.USER_SESSION_KEY);
		session.removeAttribute(Constants.USER_RIGHT);
		session.removeAttribute(Constants.USER_RIGHT_MENU);
		return new RedirectView(servletContext.getContextPath() + "/login.html");
	}
	
	/**
	 * 修改密码
	 * @param password
	 * @param old_pwd
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/modifyPwd")
	public Map<String, String> modifyPwd(String password, String old_pwd, HttpSession session) {
		Map<String, String> result = new HashMap<String, String>();
		if (null == session.getAttribute(Constants.USER_SESSION_KEY)) {
			result.put("optFlag", "N");
			result.put("optDesc", "登录超时！");
			return result;
		}
		Map<String, Object> user = (Map<String, Object>) session.getAttribute(Constants.USER_SESSION_KEY);
		user = sysUserService.selectSysUserById(String.valueOf(user.get("user_id")));
		if (null != user) {
			String user_pwd = String.valueOf(user.get("password"));
			old_pwd = new MD5().getMD5ofStr(old_pwd.trim());
			if (!old_pwd.equals(user_pwd)) {
				result.put("optFlag", "N");
				result.put("optDesc", "原始密码输入不正确！");
				return result;
			}
			password = new MD5().getMD5ofStr(password.trim());
			user.put("password", password);
			sysUserService.updateUserPwd(user);
			result.put("optFlag", "Y");
		}
		return result;
	}
	
	/**
	 * 用户信息返回
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/userInfo")
	public Map<String, Object> userRight(HttpSession session) {
		Map<String, Object> user = (Map<String, Object>) session.getAttribute(Constants.USER_SESSION_KEY);
		user.put("menus", (List<Map<String, Object>>) session.getAttribute(Constants.USER_RIGHT_MENU));
		user.put("rights", (Set<String>) session.getAttribute(Constants.USER_RIGHT));
		return user;
	}
	
	/**
	 * 初始化用户信息，json
	 * @param user_id
	 * @param session
	 */
	private void initUserRight(String user_id, HttpSession session) {

		List<Map<String, Object>> rights = sysUserService.findAllRightByUser(user_id);
		Set<String> userRights = new HashSet<String>();
		Map<String, List<Map<String, Object>>> parentidMap = new HashMap<String, List<Map<String, Object>>>();
		String parentid = "";
		String lastparentid = "";
		List<Map<String, Object>> listorgan = null;
		for (Map<String, Object> map : rights) {
			
			if (null != map.get("access_value"))
				userRights.add(map.get("access_value")+"");
			if(String.valueOf(map.get("access_type")).equals("2"))
				continue;
			parentid = String.valueOf(map.get("parent_id"));
			if (parentid == null)
				parentid = "0";
			if (!lastparentid.equals(parentid)) {
				if (listorgan != null)
					parentidMap.put(lastparentid, listorgan);
				listorgan = new ArrayList<Map<String, Object>>();
				lastparentid = parentid;
			}
			listorgan.add(map);
			
		}
		parentidMap.put(lastparentid, listorgan);

		session.setAttribute(Constants.USER_RIGHT, userRights);
		session.setAttribute(Constants.USER_RIGHT_MENU, changeTreeNodeList(parentidMap, "0"));
	}

	/**
	 * 将权限信息转换为树形结构List
	 * 
	 * @param parentidMap
	 * @param parentid
	 * @return
	 */
	private List<Map<String, Object>> changeTreeNodeList(Map<String, List<Map<String, Object>>> parentidMap,
			String parentid) {

		List<Map<String, Object>> root = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> list = (List<Map<String, Object>>) parentidMap.get(parentid);
		if (null != list) {
			root.addAll(list);
			for (int i = 0; i < list.size(); ++i) {
				HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
				String id = String.valueOf(map.get("right_id"));
				map.put("child", parentidMap.get(id));

			}
		}
		return root;
	}
	
	/**
	 * 用户列表
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userList")
	public Map<String, Object> userList(@RequestParam Map<String, String> param) {
		Map<String, Object> result = new HashMap<String, Object>();
		int count = sysUserService.countSysUser(param);
		List<Map<String, Object>> data = sysUserService.findSysUser(param);
		result.put("iTotalRecords", count);
		result.put("iTotalDisplayRecords", count);
		result.put("aaData", data);
		return result;
	}
	
	/**
	 * 用户角色，部门信息返回
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userRelated")
	public Map<String, Object> userRelated() {
		Map<String, Object> result = new HashMap<String, Object>();
		List<Map<String, Object>> roles = sysUserService.findSysRole();
		result.put("roles", roles);
		result.put("depts", sysUserService.findSysDept());
		return result;
	}
	
	/**
	 * 添加系统用户
	 * @param param
	 * @param role_ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addSysUser")
	public Map<String, Object> addSysUser(@RequestParam Map<String, Object> param, String[] role_ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> user = sysUserService.selectSysUserById(param.get("user_id") + "");
			if (null != user) {
				result.put("optFlag", "N");
				result.put("optDesc", "用户帐号已存在!");
				return result;
			}

			sysUserService.insertIntoSysUser(param, role_ids);
			result.put("optFlag", "Y");
			result.put("optDesc", "添加用户成功!");
		} catch (Exception e) {
			result.put("optFlag", "E");
			result.put("optDesc", "发生错误,请稍后重试!");
		}
		return result;
	}

	/**
	 * 修改用户信息
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editSysUser")
	public Map<String, Object> editSysUser(@RequestParam Map<String, Object> param, String[] role_ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> user = sysUserService.selectSysUserById(param.get("user_id") + "");
			if (null == user) {
				result.put("optFlag", "N");
				result.put("optDesc", "用户不存在!");
				return result;
			}
			sysUserService.updateSysUser(param, role_ids);
			result.put("optFlag", "Y");
			result.put("optDesc", "添加用户成功!");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("optFlag", "E");
			result.put("optDesc", "发生错误,请稍后重试!");
		}
		return result;
	}
	
	/**
	 * 删除部门
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delDept")
	public Map<String, Object> delDept(@RequestParam Map<String, String> param) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			sysUserService.delDept(param.get("dept_id"));
			result.put("optFlag", "Y");
			result.put("optDesc", "删除成功!");
		} catch (Exception e) {
			result.put("optFlag", "E");
			result.put("optDesc", "发生错误,请稍后重试!");
		}
		return result;
	}
	
	/**
	 * 查找用户信息
	 * @param user_id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/findUserInfo")
	public Map<String, Object> findUserInfo(String user_id) {
		Map<String, Object> result = sysUserService.selectSysUserById(user_id);
		result.remove("password");
		result.put("role_id", sysUserService.findSysUserRoleByUserId(user_id));
		return result;
	}
	
	/**
	 * 删除用户信息
	 * @param user_id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delSysUser")
	public Map<String, Object> delSysUser(String user_id) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			sysUserService.deleteSysUser(user_id);
			result.put("optFlag", "Y");
			result.put("optDesc", "删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("optFlag", "E");
			result.put("optDesc", "发生错误,请稍后重试!");
		}
		return result;
	}
	
	/**
	 * 添加部门
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addDept")
	public Map<String, Object> addDept(@RequestParam Map<String, String> param) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			List<Map<String, Object>> list = sysUserService.getDeptByCode(param.get("dept_code"));
			if (list.size() > 0) {
				result.put("optFlag", "N");
				result.put("optDesc", "部门编号已存在!");
				return result;
			}
			list = sysUserService.getDeptByName(param.get("dept_name"));
			if (list.size() > 0) {
				result.put("optFlag", "N");
				result.put("optDesc", "部门名称已存在!");
				return result;
			}
			sysUserService.addDept(param);
			result.put("optFlag", "Y");
			result.put("dept", param);
			result.put("optDesc", "添加成功!");
		} catch (Exception e) {
			result.put("optFlag", "E");
			result.put("optDesc", "发生错误,请稍后重试!");
		}
		return result;
	}
	
	/**
	 * 角色列表
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/roleList")
	public Map<String, Object> roleList(@RequestParam Map<String, String> param) {
		Map<String, Object> result = new HashMap<String, Object>();
		int count = sysUserService.countSysRole(param);
		List<Map<String, Object>> data = sysUserService.findSysRole(param);
		result.put("iTotalRecords", count);
		result.put("iTotalDisplayRecords", count);
		result.put("aaData", data);
		return result;
	}
	
	/**
	 * 删除角色
	 * @param role_id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delSysRole")
	public Map<String, Object> delSysRole(String role_id) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			sysUserService.deleteRole(role_id);
			result.put("optFlag", "Y");
			result.put("optDesc", "删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("optFlag", "E");
			result.put("optDesc", "发生错误,请稍后重试!");
		}
		return result;
	}
	
	/**
	 * 添加角色
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addSysRole")
	public Map<String, Object> addSysRole(@RequestParam Map<String, Object> param) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			Map<String, Object> role = this.sysUserService.findRoleInfoByRoleCode(param.get("role_code")+"");
			if (null != role) {
				result.put("optFlag", "N");
				result.put("optDesc", "角色编号已存在!");
				return result;
			}
			role = this.sysUserService.findRoleInfoByRoleName(param.get("role_name")+"");
			if (null != role) {
				result.put("optFlag", "N");
				result.put("optDesc", "角色名称已存在!");
				return result;
			}
			sysUserService.insertRoleInfo(param);
			result.put("optFlag", "Y");
			result.put("optDesc", "添加角色成功!");
		} catch (Exception e) {
			result.put("optFlag", "E");
			result.put("optDesc", "发生错误,请稍后重试!");
			e.printStackTrace();
		}
		return result;
	}
	
	
	/**
	 *权限列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/rightList")
	public Map<String, Object> rightList() {
		Map<String, Object> result = new HashMap<String, Object>();
		int count = sysUserService.countAllRights();
		List<Map<String, Object>> data = sysUserService.findAllRights();
		result.put("iTotalRecords", count);
		result.put("iTotalDisplayRecords", count);
		result.put("aaData", data);
		return result;
	}
	
	
	/**
	 * 查找角色
	 * @param role_id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/findRole")
	public Map<String, Object> findRole(String role_id) {
		Map<String, Object> role = sysUserService.findRoleById(role_id);
		List<String> rights = sysUserService.findRightsIdByRoleId(role_id);
		role.put("rights", JSONArray.fromObject(rights).toString());
		role.put("optFlag", "Y");
		return role;
	}
	
	/**
	 * 编辑系统角色
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editSysRole")
	public Map<String, Object> editSysRole(@RequestParam Map<String, String> param) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> role = this.sysUserService.findRoleInfoByRoleIdAndName(param);
			if (null != role) {
				result.put("optFlag", "N");
				result.put("optDesc", "角色名称已存在!");
				return result;
			}
			sysUserService.updateRoleInfo(param);
			result.put("optFlag", "Y");
			result.put("optDesc", "保存角色成功!");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("optFlag", "E");
			result.put("optDesc", "发生错误,请稍后重试!");
			e.printStackTrace();
		}
		return result;
	}
}
